package com.example.juc.until;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadAndWriteLock {
    public static void main(String[] args) {

        MyCache myCache = new MyCache();
        for (int i = 1; i <6 ; i++) {
            final int temp =i;
            new Thread( ()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <6 ; i++) {
            final int temp =i;
            new Thread( ()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }

    }
    static class MyCache{
       // private ReadWriteLock readWriteLock;
        private volatile Map<String,Object> map =new HashMap<>();
        //读写锁 读的时候可以一块读（共享锁） 写的时候单个写（独占锁）
        //加入写锁之后 在多线程情况下  可以单个有序执行
        private   ReadWriteLock readWriteLock =new ReentrantReadWriteLock();
        public void put(String key,Object value){
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"::存  开始");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"::存  完毕");
            readWriteLock.writeLock().unlock();
        }
        //取  读
        public void  get(String Key){
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"::取  开始");
            map.get(Key);
            System.out.println(Thread.currentThread().getName()+"::取  完毕");
            readWriteLock.readLock().unlock();
        }
    }


}
